package com.classtest.DemoExpend.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.classtest.DemoExpend.bean.DbShop;
import com.classtest.DemoExpend.bean.DbUser;
import com.classtest.DemoExpend.service.DbShopInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ShopInfoController {

    @Autowired
    DbShopInfoService dbShopInfoService;

    // 获取店铺信息
    @RequestMapping("/shopInfo")
    public String shopInfo(HttpServletRequest request, DbShop dbShop) {
        DbUser user = (DbUser) request.getSession().getAttribute("user");
        dbShop.setUsId(user.getId());
        List<DbShop> userShopInfo = dbShopInfoService.getShopInfo(JSON.toJSONString(dbShop));
        Map<String,Object> ShopInfo = new HashMap<>();
        List<Object> list = new ArrayList<>();
        for (DbShop shopInfo: userShopInfo){
            Map<String,Object> res = new HashMap<>();
            res.put("shopId",shopInfo.getShopId());
            res.put("shopName",shopInfo.getShopName());
            res.put("shopInfo",shopInfo.getShopInfo());
            list.add(res);
        }
        ShopInfo.put("shopInfo",list);
        return JSON.toJSONString(ShopInfo);
    }
    // 修改店铺信息
    @RequestMapping("/updateShopInfo")
    public String updateShopInfo(@RequestBody String json, HttpSession session) {
        Map<String,Object> updateShop = new HashMap<>();
        try {
            DbUser user = (DbUser)session.getAttribute("user");
            if(user != null){
                DbShop user1 = JSONObject.parseObject(json,DbShop.class);
                dbShopInfoService.updateShopInfo(JSON.toJSONString(user1));
                updateShop.put("flag","ok");
            }else {
                updateShop.put("flag","error");
                updateShop.put("resMsg","还没有登录");
            }
        } catch (Exception e) {
            updateShop.put("error",e.toString());
        }
        return JSON.toJSONString(updateShop);
    }
}
